package com.crm.system.service.impl.cluePoolManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.CluePoolNatureEnum;
import com.crm.common.model.Enum.CluePoolStatusEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.cluePoolManager.CluePoolCompany;
import com.crm.model.entity.cluePoolManager.CluePoolPublic;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.qo.cluePoolManager.*;
import com.crm.model.vo.cluePoolManager.CluePoolPubliclOpenSeaVO;
import com.crm.model.vo.cluePoolManager.CluePoolUpdateVO;
import com.crm.model.vo.cluePoolManager.CluePoolVO;
import com.crm.service.cluePoolManager.CluePoolCompanyDbService;
import com.crm.service.cluePoolManager.CluePoolPublicDbService;
import com.crm.system.service.cluePoolManager.*;
import com.crm.system.service.permissionManagement.SysCompanyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author luojie
 * @date 2020/12/24 11:15
 */
@Service
public class CluePoolPublicServiceImpl implements CluePoolPublicService {

    @Autowired
    private SysCompanyService sysCompanyService;
    @Autowired
    private CluePoolPublicDbService cluePoolPublicDbService;
    @Autowired
    private CluePoolCompanyService cluePoolCompanyService;
    @Autowired
    private CluePoolRuleService cluePoolRuleService;
    @Autowired
    private CluePoolDistributionService cluePoolDistributionService;
    @Autowired
    private CluePoolManagerService cluePoolManagerService;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addCluePoolPublic(CluePoolPublicQO cluePoolPublicQO) {
        //1、根据线索池名称判断线索池是否存在，存在则添加线索池
        CluePoolPublic cluePoolPublic = cluePoolPublicDbService.selectCluePoolPublicByName(cluePoolPublicQO.getCluePoolName());
        if(cluePoolPublic==null){
            String cluePoolId = addCluePoolPublicModel(cluePoolPublicQO);
            if(cluePoolPublicQO.getNature()== CluePoolNatureEnum.BRANCH_PUBLIC_POOL.getCluePoolNatureCode()){
                //2、添加公司表
                cluePoolCompanyService.addPoolCompany(cluePoolPublicQO.getCompanyIdList(),cluePoolId);
            }else if(cluePoolPublicQO.getNature()== CluePoolNatureEnum.PRIVATE_POOL.getCluePoolNatureCode()){
                //2、（1）添加管理表
                cluePoolManagerService.insertCluePoolManagerByCreatePeople(cluePoolId);
                //2、（2）添加公司表(个人公司)
                cluePoolCompanyService.addCreatePeopleCompany(cluePoolId);
            }
            //3、添加规则表
            cluePoolRuleService.addCluePoolRule(cluePoolPublicQO,cluePoolId);
            return true;
        }else{
            return false;
        }
    }



    String addCluePoolPublicModel(CluePoolPublicQO cluePoolPublicQO){
        //获取当前用户
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String cluePoolPublicId = CommonUtils.getGUID();
        CluePoolPublic cluePoolPublic = new CluePoolPublic();
        cluePoolPublic.setCluePoolPublicId(cluePoolPublicId);
        cluePoolPublic.setCluePoolName(cluePoolPublicQO.getCluePoolName());
        //判断当前用户是否是超级管理员
        //如果不是超级管理员就
        Boolean ifAdmin = CommonUtils.isAdmin(userAccount.getUserId());
        if(!ifAdmin){
            cluePoolPublic.setCompanyId(userAccount.getCompanyId());
            //公司名称
            SysCompany sysCompany = sysCompanyService.selectSysCompanyById(userAccount.getCompanyId());
            cluePoolPublic.setCompanyName(sysCompany.getCompanyName());
        }
        cluePoolPublic.setProvinceId(cluePoolPublicQO.getProvinceId());
        cluePoolPublic.setProvinceName(cluePoolPublicQO.getProvinceName());
        cluePoolPublic.setCityId(cluePoolPublicQO.getCityId());
        cluePoolPublic.setCityName(cluePoolPublicQO.getCityName());
        cluePoolPublic.setIndustry(cluePoolPublicQO.getIndustry());
        cluePoolPublic.setSource(cluePoolPublicQO.getSource());
        cluePoolPublic.setTag(cluePoolPublicQO.getTag());
        cluePoolPublic.setPoolType(cluePoolPublicQO.getPoolType());
        cluePoolPublic.setAllocation(cluePoolPublicQO.getAllocation());
        cluePoolPublic.setCapacity(cluePoolPublicQO.getCapacity());
        cluePoolPublic.setNature(cluePoolPublicQO.getNature());
        cluePoolPublic.setConversionMethod(cluePoolPublicQO.getConversionMethod());
        cluePoolPublic.setPoolState(CluePoolStatusEnum.TURN_ON.getCluePoolStatus());
        cluePoolPublic.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        cluePoolPublic.setPermanent(cluePoolPublicQO.getPermanent());
        Integer permanent = 0; //没有设定永久有效
        if(cluePoolPublicQO.getPermanent()==permanent){
            cluePoolPublic.setEffectiveTime(cluePoolPublicQO.getEffectiveTime());
        }
        Integer defaultMark = 0;//不是默认池子
        cluePoolPublic.setDefaultMark(defaultMark);
        cluePoolPublic.setCreatePeopleId(userAccount.getAccountId());
        cluePoolPublic.setCreateTm(new Date());
        cluePoolPublic.setUpdatePeopleId(userAccount.getAccountId());
        cluePoolPublic.setUpdateTm(new Date());
        Boolean result = cluePoolPublicDbService.insertCluePoolPublic(cluePoolPublic);
        return cluePoolPublicId;
    }

    /**
     * 管理系统--删除线索池(私有池、分公司公有池、全国池子)
     * @param cluePoolPublicId ---线索池ID
     * @param accountId ---操作人ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean deleteCluePoolPublic(String cluePoolPublicId,String accountId) {
        //1：删除线索池(cp_clue_pool_public)
        CluePoolPublic cluePoolPublic = new CluePoolPublic();
        cluePoolPublic.setCluePoolPublicId(cluePoolPublicId);//线索池ID
        cluePoolPublic.setDeleteStatus((short)StatusCodeEnum.DELETE_CODE.getState());//删除状态
        cluePoolPublic.setUpdatePeopleId(accountId);//用户ID
        cluePoolPublic.setUpdateTm(new Date());//更新时间
        cluePoolPublicDbService.deleteCluePoolPublic(cluePoolPublic);
        //2：根据线索池ID查询其线索ID
        return null;
    }

    /**
     * @author wll
     * info 用户模块-线索池管理-线索池公海表单 (全国)
     * @return
     */
    @Override
    public DhPageInfo<CluePoolPubliclOpenSeaVO> getCluePoolPublicInfo(CluePoolOpenSeaQO cluePoolOpenSeaQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        Integer dateUnit = 0;
        if (StringUtils.isNotEmpty(cluePoolOpenSeaQO.getDateType())) {
            if ("thisWeek".equals(cluePoolOpenSeaQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(cluePoolOpenSeaQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(cluePoolOpenSeaQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
        }

        //拼凑表格排序内容
        String order = "p.default_mark desc"; //是否是默认池子：0-不是默认；1-默认池子
        if(StringUtils.isNotEmpty(sortName) && StringUtils.isNotEmpty(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order= order + ",p.create_tm " + sortOrder;
                }
                break;
                case "poolType":
                {
                    order= order + ",p.pool_type " + sortOrder;
                }
                break;
                default:
                    break;
            }

        }
        List list = new ArrayList();//兼容tab我参与的
        Map map = new HashMap();
        map.put("list",list);
        map.put("cluePoolOpenSeaQO",cluePoolOpenSeaQO);
        map.put("dateUnit",dateUnit);
        map.put("order",order);
        List<CluePoolPubliclOpenSeaVO> cluePoolPubliclOpenSeaVOList = cluePoolPublicDbService.selectCluePoolPublicInfo(map);
        PageInfo<CluePoolPubliclOpenSeaVO> pageInfo = new PageInfo<CluePoolPubliclOpenSeaVO>(cluePoolPubliclOpenSeaVOList);
        return new DhPageInfo<CluePoolPubliclOpenSeaVO>(pageInfo, cluePoolPubliclOpenSeaVOList);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean updateCluePoolRule(CluePoolRuleQO cluePoolRuleQO) {
        //获取当前用户
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String allocation = cluePoolRuleQO.getAllocation();
        String cluePoolId = cluePoolRuleQO.getPoolId();
        if(!StringUtils.isBlank(allocation) && !StringUtils.isBlank(cluePoolId)){
            CluePoolPublic cluePoolPublic = cluePoolPublicDbService.selectCluePoolPublicById(cluePoolId);
            cluePoolPublic.setAllocation(Integer.parseInt(allocation));
            cluePoolPublic.setUpdatePeopleId(userAccount.getAccountId());
            cluePoolPublic.setUpdateTm(new Date());
            cluePoolPublicDbService.updateCluePoolPublicById(cluePoolPublic);
            cluePoolRuleService.deleteCluePoolRuleByCluePoolId(cluePoolId);
            cluePoolDistributionService.deleteCluePoolDistributionByCluePoolId(cluePoolId);
            cluePoolRuleService.updateCluePoolRule(cluePoolRuleQO,cluePoolId);
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean saveCluePoolPermissionAndDetail(CluePoolPermissionAndDetailQO cluePoolPermissionAndDetailQO) {
        //线索池id
        String cluePoolId = cluePoolPermissionAndDetailQO.getCluePoolId();
        //1、修改线索池详情
        CluePoolPublic cluePoolPublic = new CluePoolPublic();
        cluePoolPublic.setCluePoolPublicId(cluePoolId);
        cluePoolPublic.setPoolDetail(cluePoolPermissionAndDetailQO.getPoolDetail());
        cluePoolPublicDbService.updateCluePoolPublicById(cluePoolPublic);

        //2、保存线索池管理人员
        // 管理人员id的List
        List<JSONObject> managerPeopleIdList = cluePoolPermissionAndDetailQO.getManagerPeopleIdList();
        if(managerPeopleIdList.size()>0){
            //删除线索池管理表数据
            cluePoolManagerService.deleteCluePoolManager(cluePoolId);
            //新增线索池管理表数据
            cluePoolManagerService.insertCluePoolManager(cluePoolId,managerPeopleIdList);
        }

        //3、保存线索池使用人员
        List<JSONObject> usePeopleList = cluePoolPermissionAndDetailQO.getUsePeopleList();
        if(usePeopleList.size()>0){
            //删除线索池使用个人
            String permissionType = "2";
            cluePoolCompanyService.deleteUsePeople(cluePoolId,permissionType);
            //新增线索池使用个人
            cluePoolCompanyService.addUsePeople(cluePoolId,usePeopleList);
        }

        //4、保存使用公司id的List
        List<String> companyIdList = cluePoolPermissionAndDetailQO.getUseCompanyIdList();
        if(companyIdList.size()>0){
            //删除线索池使用组公司id
            String permissionType = "1";
            cluePoolCompanyService.deleteUsePeople(cluePoolId,permissionType);
            //新增线索池使用组公司id
            cluePoolCompanyService.addUserCompany(cluePoolId,companyIdList);
        }
        return true;
    }

    @Override
    public CluePoolPublic selectCluePoolPublicById(String cluePoolPublicId) {
        CluePoolPublic cluePoolPublic = cluePoolPublicDbService.selectCluePoolPublicById(cluePoolPublicId);
        return cluePoolPublic;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean updateCluePoolPublic(CluePoolUpdateQO cluePoolUpdateQO) {
        CluePoolPublic cluePoolPublic = cluePoolPublicDbService.selectCluePoolPublicUpdateByNameAndId(cluePoolUpdateQO.getCluePoolName(),cluePoolUpdateQO.getCluePoolId());
        if(cluePoolPublic==null){
            CluePoolPublic cluePoolPublicNew = new CluePoolPublic();
            cluePoolPublicNew.setCluePoolPublicId(cluePoolUpdateQO.getCluePoolId());
            cluePoolPublicNew.setCluePoolName(cluePoolUpdateQO.getCluePoolName());
            cluePoolPublicNew.setSource(cluePoolUpdateQO.getSource());
            cluePoolPublicNew.setProvinceName(cluePoolUpdateQO.getProvinceName());
            cluePoolPublicNew.setProvinceId(cluePoolUpdateQO.getProvinceId());
            cluePoolPublicNew.setCityName(cluePoolUpdateQO.getCityName());
            cluePoolPublicNew.setCityId(cluePoolUpdateQO.getCityId());
            cluePoolPublicNew.setIndustry(cluePoolUpdateQO.getIndustry());
            cluePoolPublicNew.setPermanent(cluePoolUpdateQO.getPermanent());
            Integer permanent = 0; //没有设定永久有效
            if(cluePoolUpdateQO.getPermanent()==permanent){
                cluePoolPublicNew.setEffectiveTime(cluePoolUpdateQO.getEffectiveTime());
            }
            cluePoolPublicNew.setPoolType(cluePoolUpdateQO.getPoolType());
            cluePoolPublicNew.setTag(cluePoolUpdateQO.getTag());
            cluePoolPublicNew.setCapacity(cluePoolUpdateQO.getCapacity());
            cluePoolPublicNew.setConversionMethod(cluePoolUpdateQO.getConversionMethod());
            cluePoolPublicNew.setNature(cluePoolUpdateQO.getNature());
            if(cluePoolUpdateQO.getOldNature()==CluePoolNatureEnum.BRANCH_PUBLIC_POOL.getCluePoolNatureCode()){
                cluePoolCompanyService.deleteUsePeople(cluePoolUpdateQO.getCluePoolId(),"1");
            }
            cluePoolPublicDbService.updateCluePoolPublicById(cluePoolPublicNew);

            //如果是分公司公有池就保存公司
            if(cluePoolUpdateQO.getNature()==CluePoolNatureEnum.BRANCH_PUBLIC_POOL.getCluePoolNatureCode()){
              cluePoolCompanyService.addPoolCompany(cluePoolUpdateQO.getCompanyIdList(),cluePoolUpdateQO.getCluePoolId());
            }
            return true;
        }else {
            return false;
        }
    }

    @Override
    public CluePoolUpdateVO selectCluePoolUpdateInfo(String cluePoolId) {
        CluePoolPublic cluePoolPublic = cluePoolPublicDbService.selectCluePoolPublicById(cluePoolId);
        CluePoolUpdateVO cluePoolUpdateVO = new CluePoolUpdateVO();
        cluePoolUpdateVO.setCluePoolId(cluePoolPublic.getCluePoolPublicId());
        cluePoolUpdateVO.setCluePoolName(cluePoolPublic.getCluePoolName());
        cluePoolUpdateVO.setCapacity(cluePoolPublic.getCapacity());
        cluePoolUpdateVO.setCityId(cluePoolPublic.getCityId());
        cluePoolUpdateVO.setCityName(cluePoolPublic.getCityName());
        cluePoolUpdateVO.setProvinceId(cluePoolPublic.getProvinceId());
        cluePoolUpdateVO.setProvinceName(cluePoolPublic.getProvinceName());
        cluePoolUpdateVO.setIndustry(cluePoolPublic.getIndustry());
        cluePoolUpdateVO.setSource(cluePoolPublic.getSource());
        cluePoolUpdateVO.setConversionMethod(cluePoolPublic.getConversionMethod());
        cluePoolUpdateVO.setNature(cluePoolPublic.getNature());
        cluePoolUpdateVO.setPermanent(cluePoolPublic.getPermanent());
        cluePoolUpdateVO.setPoolType(cluePoolPublic.getPoolType());
        Integer permanent = 0; //没有设定永久有效
        if(cluePoolPublic.getPermanent()==permanent){
            cluePoolUpdateVO.setEffectiveTime(cluePoolPublic.getEffectiveTime());
        }
        cluePoolUpdateVO.setTag(cluePoolPublic.getTag());
        //分公司性质线索池需要查询所选公司id
        if(cluePoolPublic.getNature()==CluePoolNatureEnum.BRANCH_PUBLIC_POOL.getCluePoolNatureCode()){
            List<CluePoolCompany> cluePoolCompanyList = cluePoolCompanyService.selectCompanyByPoolId(cluePoolId);
            List<String> companyIdList = new ArrayList<>();
            cluePoolCompanyList.stream().forEach(cluePoolCompany -> {
                companyIdList.add(cluePoolCompany.getCluePollCompanyId());
            });
            cluePoolUpdateVO.setCompanyIdList(companyIdList);
        }

        return cluePoolUpdateVO;
    }
}
